package com.example.myproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.myproject.dto.message.ConversationDTO;
import com.example.myproject.dto.message.MessageDTO;
import com.example.myproject.mapper.ConversationMapper;
import com.example.myproject.mapper.MessageMapper;
import com.example.myproject.mapper.UserMapper;
import com.example.myproject.model.Conversation;
import com.example.myproject.model.Message;
import com.example.myproject.model.User;
import com.example.myproject.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private ConversationMapper conversationMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<ConversationDTO> getUserConversations(Long userId) {
        List<Conversation> conversations = conversationMapper.findByUserId(userId);
        return conversations.stream()
                .map(conversation -> convertToConversationDTO(conversation, userId))
                .collect(Collectors.toList());
    }

    @Override
    public List<MessageDTO> getConversationMessages(Long conversationId) {
        List<Message> messages = messageMapper.findByConversationId(conversationId);
        return messages.stream()
                .map(this::convertToMessageDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public MessageDTO sendMessage(Long fromUserId, Long toUserId, String content) {
        // 1. 查找或创建会话
        Conversation conversation = findOrCreateConversation(fromUserId, toUserId);

        // 2. 创建新消息
        Message message = new Message();
        message.setConversationId(conversation.getId());
        message.setFromUserId(fromUserId);
        message.setToUserId(toUserId);
        message.setContent(content);
        message.setSentAt(LocalDateTime.now());
        message.setIsRead(false);
        message.setStatus("SENT");

        // 3. 更新会话的最后消息时间和未读计数
        conversation.setLastMessageTime(message.getSentAt());
        // 根据接收者更新对应的未读计数
        if (conversation.getUser1Id().equals(toUserId)) {
            conversation.setUnreadCountUser1(conversation.getUnreadCountUser1() + 1);
        } else {
            conversation.setUnreadCountUser2(conversation.getUnreadCountUser2() + 1);
        }

        // 4. 保存消息和更新会话
        messageMapper.insert(message);
        conversationMapper.updateById(conversation);

        return convertToMessageDTO(message);
    }
    /**
     * 查找或创建两个用户之间的会话
     * @param user1Id 用户1的ID
     * @param user2Id 用户2的ID
     * @return 会话对象
     */
    private Conversation findOrCreateConversation(Long user1Id, Long user2Id) {
        // 确保user1Id < user2Id，这样可以保证两个用户之间的会话唯一性
        if (user1Id > user2Id) {
            Long temp = user1Id;
            user1Id = user2Id;
            user2Id = temp;
        }

        // 查找现有会话
        Conversation conversation = conversationMapper.findByUserIds(user1Id, user2Id);

        // 如果会话不存在，创建新会话
        if (conversation == null) {
            conversation = new Conversation();
            conversation.setUser1Id(user1Id);
            conversation.setUser2Id(user2Id);
            conversation.setLastMessageTime(LocalDateTime.now());
            conversation.setUnreadCountUser1(0);
            conversation.setUnreadCountUser2(0);
            conversationMapper.insert(conversation);
        }

        return conversation;
    }


    @Override
    @Transactional
    public void markMessageAsReadByMessageId(Long messageId, Long userId) {
        // 1. 先查询消息，获取会话ID
        Message message = messageMapper.selectById(messageId);
        if (message == null) {
            return;
        }

        // 2. 验证消息接收者是否为当前用户
        if (!message.getToUserId().equals(userId)) {
            return;
        }

        // 3. 更新该消息的已读状态
        Message updateMessage = new Message();
        updateMessage.setId(messageId);
        updateMessage.setIsRead(true);
        messageMapper.updateById(updateMessage);

        // 4. 更新会话中该用户的所有未读消息
        QueryWrapper<Message> wrapper = new QueryWrapper<>();
        wrapper.eq("conversation_id", message.getConversationId())
                .eq("to_user_id", userId)
                .eq("is_read", false);

        Message batchUpdateMessage = new Message();
        batchUpdateMessage.setIsRead(true);
        messageMapper.update(batchUpdateMessage, wrapper);

        // 5. 更新会话的未读计数
        Conversation conversation = conversationMapper.selectById(message.getConversationId());
        if (conversation != null) {
            if (conversation.getUser1Id().equals(userId)) {
                conversation.setUnreadCountUser1(0);
            } else {
                conversation.setUnreadCountUser2(0);
            }
            conversationMapper.updateById(conversation);
        }
    }

    @Override
    public MessageDTO getLastMessage(Long conversationId) {
        Message lastMessage = messageMapper.findLastMessageByConversationId(conversationId);
        return lastMessage != null ? convertToMessageDTO(lastMessage) : null;
    }
    private ConversationDTO convertToConversationDTO(Conversation conversation, Long currentUserId) {
        ConversationDTO dto = new ConversationDTO();
        dto.setId(conversation.getId());

        // 根据当前用户ID确定对方用户信息
        if (conversation.getUser1Id().equals(currentUserId)) {
            // 当前用户是user1
            dto.setUser1Id(conversation.getUser1Id());
            dto.setUser2Id(conversation.getUser2Id());
            dto.setUser1Name(userMapper.selectById(conversation.getUser1Id()).getUserName());
            dto.setUser2Name(userMapper.selectById(conversation.getUser2Id()).getUserName());
            dto.setUser1Avatar(userMapper.selectById(conversation.getUser1Id()).getAvatar());
            dto.setUser2Avatar(userMapper.selectById(conversation.getUser2Id()).getAvatar());
            dto.setUnreadCount(conversation.getUnreadCountUser1()); // 当前用户的未读数
        } else {
            // 当前用户是user2
            dto.setUser1Id(conversation.getUser2Id());
            dto.setUser2Id(conversation.getUser1Id());
            dto.setUser1Name(userMapper.selectById(conversation.getUser2Id()).getUserName());
            dto.setUser2Name(userMapper.selectById(conversation.getUser1Id()).getUserName());
            dto.setUser1Avatar(userMapper.selectById(conversation.getUser2Id()).getAvatar());
            dto.setUser2Avatar(userMapper.selectById(conversation.getUser1Id()).getAvatar());
            dto.setUnreadCount(conversation.getUnreadCountUser2()); // 当前用户的未读数
        }

        dto.setLastMessageTime(conversation.getLastMessageTime());

        // 获取最后一条消息
        MessageDTO lastMessage = getLastMessage(conversation.getId());
        if (lastMessage != null) {
            dto.setLastMessage(lastMessage.getContent());
        }

        return dto;
    }

    private MessageDTO convertToMessageDTO(Message message) {
        MessageDTO dto = new MessageDTO();
        dto.setId(message.getId());
        dto.setConversationId(message.getConversationId());
        dto.setFromUserId(message.getFromUserId());
        dto.setToUserId(message.getToUserId());
        dto.setContent(message.getContent());
        dto.setSentAt(message.getSentAt());
        dto.setIsRead(message.getIsRead());

        User fromUser = userMapper.selectById(message.getFromUserId());
        if (fromUser != null) {
            dto.setFromUserName(fromUser.getUserName());
            dto.setFromUserAvatar(fromUser.getAvatar());
        }

        User toUser = userMapper.selectById(message.getToUserId());
        if (toUser != null) {
            dto.setToUserName(toUser.getUserName());
            dto.setToUserAvatar(toUser.getAvatar());
        }

        return dto;
    }
}